// pages/schedule/schedule.ts (with enhanced logging for date parsing)
import { IAppOption } from "../../app"; // Ensure this path is correct for your app.ts

const app = getApp<IAppOption>();

interface IScheduleBackend {
  id: number;
  speaker: string;
  content: string;
  created_at: string; // ISO String from backend
  parsed_schedule_time?: string | null; // ISO String from backend
  reminder_trigger_time?: string | null; // ISO String from backend
  llm_parse_status: string;
  is_reminded: boolean;
}

interface IScheduleDisplayItem extends IScheduleBackend {
  created_at_formatted: string;
  parsed_schedule_time_formatted: string;
  reminder_trigger_time_formatted: string;
  llm_parse_status_display: string;
}

interface ISchedulePageData {
  schedules: IScheduleDisplayItem[];
  isLoading: boolean;
  hasMoreData: boolean; // For future pagination
  errorLoading: boolean;
}

interface ISchedulePageInstance {
  data: ISchedulePageData;
  onLoad: () => void;
  fetchSchedules: (isRefresh?: boolean) => void;
  formatDisplayTime: (isoString?: string | null) => string;
  mapStatusToDisplay: (status: string) => string;
  onRefreshSchedules: () => void;
  onScrollToLower: () => void; // For future pagination
  // setData will be available on `this` automatically
}

Page<ISchedulePageData, ISchedulePageInstance>({
  data: {
    schedules: [],
    isLoading: false,
    hasMoreData: true, // Assume there might be more initially
    errorLoading: false,
  },

  onLoad() {
    this.fetchSchedules(true);
  },

  fetchSchedules(isRefresh = false) {
    if (this.data.isLoading) return;

    this.setData({
      isLoading: true,
      errorLoading: false,
      schedules: isRefresh ? [] : this.data.schedules, // Clear if refreshing
    });

    wx.request({
      url: `${app.globalData.apiBaseUrl}/schedules`, // Fetches all schedules
      method: "GET",
      success: (res: WechatMiniprogram.RequestSuccessCallbackResult<any>) => {
        if (res.statusCode === 200 && Array.isArray(res.data)) {
          const backendSchedules = res.data as IScheduleBackend[];
          console.log("Received schedules from backend:", backendSchedules);
          const displaySchedules = backendSchedules.map(s => ({
            ...s,
            created_at_formatted: this.formatDisplayTime(s.created_at),
            parsed_schedule_time_formatted: this.formatDisplayTime(s.parsed_schedule_time),
            reminder_trigger_time_formatted: this.formatDisplayTime(s.reminder_trigger_time),
            llm_parse_status_display: this.mapStatusToDisplay(s.llm_parse_status),
          }));
          
          this.setData({
            schedules: isRefresh ? displaySchedules : [...this.data.schedules, ...displaySchedules],
            hasMoreData: false, 
          });
        } else {
          console.error("Failed to fetch schedules or unexpected data format:", res);
          this.setData({ errorLoading: true });
          wx.showToast({ title: (res.data && res.data.error) || "获取日程失败", icon: "none" });
        }
      },
      fail: (err) => {
        console.error("Request failed to fetch schedules:", err);
        this.setData({ errorLoading: true });
        wx.showToast({ title: "网络请求失败", icon: "none" });
      },
      complete: () => {
        this.setData({ isLoading: false });
        wx.stopPullDownRefresh(); // If using pull-down refresh
      }
    });
  },

  onRefreshSchedules() {
    this.fetchSchedules(true);
  },

  onScrollToLower() {
    // Placeholder for future pagination
  },

  formatDisplayTime(isoString?: string | null): string {
    console.log(`Formatting time for input: '${isoString}'`);
    if (!isoString) {
      console.log(`Input '${isoString}' is null or empty, returning '-'`);
      return "-";
    }
    try {
      const standardizedIsoString = isoString.replace("T", " ");
      const parsableDateString = standardizedIsoString.replace(/-/g, "/");
      console.log(`Attempting to parse: '${parsableDateString}'`);
      const date = new Date(parsableDateString);

      if (isNaN(date.getTime())) {
        console.error(`Failed to parse date: '${parsableDateString}'. Original input: '${isoString}'. Resulting Date object:`, date);
        return "日期无效";
      }
      const year = date.getFullYear();
      const month = ("0" + (date.getMonth() + 1)).slice(-2);
      const day = ("0" + date.getDate()).slice(-2);
      const hours = ("0" + date.getHours()).slice(-2);
      const minutes = ("0" + date.getMinutes()).slice(-2);
      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
      console.log(`Successfully parsed '${parsableDateString}' to '${formattedDate}'`);
      return formattedDate;
    } catch (e: any) {
      console.error(`Exception during formatting display time for input: '${isoString}'. Error:`, e.message, e.stack);
      return "解析错误";
    }
  },

  mapStatusToDisplay(status: string): string {
    switch (status) {
      case "pending":
        return "待解析";
      case "success":
        return "解析成功";
      case "failed_to_parse":
        return "解析失败";
      case "time_passed":
        return "时间已过";
      case "reminded":
        return "已提醒";
      default:
        return status;
    }
  }
});

